package com.exl.zkclient.service;

import static java.lang.Thread.sleep;

import com.exl.zkclient.entity.Order;
import com.exl.zkclient.entity.Product;
import com.exl.zkclient.mapper.OrderMapper;
import com.exl.zkclient.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class OrderService {

  @Autowired
  ProductMapper productMapper;

  @Autowired
  OrderMapper orderMapper;

  @Transactional
  public void reduceStock(int id) throws InterruptedException {
    // 1.获取库存
    Product product = productMapper.getProduct(id);
    //模拟耗时业务处理
    sleep(1000);

    if(product.getStock() <= 0){
      throw new RuntimeException("out of stock");
    }
    // 2. 减库存
    int i = productMapper.deductStock(id);
    if(i == 1){
      Order order = new Order();
      order.setUserId(UUID.randomUUID().toString());
      order.setPid(id);
      orderMapper.insert(order);
    }else {
      throw new RuntimeException("deduct stock fail,retry");
    }
  }
}
